import os

from owl_ai.application import ImageUtils
from owl_ai.domain.chat_entity import ChatMessage
from owl_ai.graph.work_flow_graph import WorkFlowGraph
from owl_ai.service import ChatService
from owl_ai.service.agent_config_service import AiAgentConfigService
from owl_ai.service.chat_messages_service import ChatMessageService, ChatFilesService
from owl_ai.service.graph.work_flow_graph_compile import WorkFlowGraphCompile
from owl_common.config import OWLConfig


class WorkFlowAppService:

    @classmethod
    def invoke(cls, chat_message: ChatMessage):
        chat_id = chat_message.chat_id
        chat = ChatService.find_chat_by_id(chat_id)

        app_config = AiAgentConfigService.select_by_id(chat.agent_id)

        # 根据配置编译应用
        work_app = WorkFlowGraph.compile(app_config)

        # 保存用户消息
        ChatMessageService.insert_message(chat_message)

        # 查询历史消息
        chat_history = ChatMessageService.find_messages_by_chat_id(chat_id)

        # 构建__start__初始参数
        start_params = {}
        for k, v in chat_message.content.items():
            start_params[k] = v

        if chat_message.files:
            files = []
            for file_id in chat_message.files:
                save_file = ChatFilesService.find_file_by_id(file_id)
                file_path = os.path.join(OWLConfig().upload_path, save_file.path)

                if ImageUtils.is_image_file(save_file.name):
                    file_base64 = ImageUtils.convert_to_base64(file_path)
                    files.append({
                        "name": save_file.name,
                        "type": "image",
                        "contentType": "base64",
                        "content": file_base64
                    })
            start_params.update({"files": files})
        # 调用应用
        message_chunks = work_app.stream(input={
            "messages": [],
            "node_params": {
                "__start__": start_params
            },
            "agent_config": app_config,
        }, stream_mode="messages")

        return message_chunks
